// get the client
const mysql = require("mysql2");
// const mysql = require("mysql2/promise");
const config = require("../config/index");
// create the connection
// const connection = mysql.createPool({
//   ...config.mysql,
//   waitForConnections: true,
//   connectionLimit: 10,
//   // maxIdle: 10, // max idle connections, the default value is the same as `connectionLimit`
//   // idleTimeout: 60000, // idle connections timeout, in milliseconds, the default value 60000
//   queueLimit: 0,
//   enableKeepAlive: true,
//   keepAliveInitialDelay: 0
// }).promise();

let globalPool = undefined;

function connection() {
  if(typeof globalPool != 'undefined') {
    return globalPool;
  }

  globalPool = mysql.createPool({
    ...config.mysql,
    waitForConnections: true,
    connectionLimit: 10,
    // maxIdle: 10, // max idle connections, the default value is the same as `connectionLimit`
    // idleTimeout: 60000, // idle connections timeout, in milliseconds, the default value 60000
    queueLimit: 0,
    enableKeepAlive: true,
    keepAliveInitialDelay: 0
  }).promise();
  return globalPool;
}


//第一类封装 ，一般用于不传递多个参数
const query = function (sql, conditions = []) {
  return new Promise(async (resolve, reject) => {
    try {
      const conn = connection();
      const res = await conn.query(sql, conditions);
      resolve(res);
    } catch (error) {
      reject(error);
    } finally {
      // connection.end();
      // connection.releaseConnection();
      // conn.end();
    }
  });
};

module.exports = {
  query,
  connect: connection()
};
